define(['ELEMENT',
    'ELEMENTICON',
    'ELEMENTCN',
    'layer',
    'jquery',
    'Promise',
    'MenuItem',
    "MuShowImg",
    "MuTreeInput",
    "MuFileUpload",
    "MuAvatarUpload",
    "MuCascader",
    "MuTreeSelect",
    "MuIcon"
], function (ELEMENT,
             ELEMENTICON,
             ELEMENTCN,
             layer,
             $,
             Promise,
             MenuItem,
             MuShowImg,
             MuTreeInput,
             MuFileUpload,
             MuAvatarUpload,
             MuCascader,
             MuTreeSelect,
             MuIcon
) {
    const {ElMessage, ElLoading, ElMessageBox} = ELEMENT
    const common = {
        config: {
            color: {},
            notInField: [
                'sort',
                'order',
                'offset',
                'limit',
                'page',
                'keyField',
                'q_word',
                'keyValue',
                'showField',
                'searchField',
                'custom',
                'isTree',
                'isHtml',
                'orderBy',
                'andOr',
                'pageSize',
                'pageNumber',
            ],
            form: null
        },
        /**
         * 加载element
         * @param app
         */
        load(app, isIndex = false, components = []) {
            app.use(ELEMENT, {
                locale: ELEMENTCN
            })
            // console.log(ElementPlusIconsVue)
            for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
                // console.log(key)
                app.component(key, component)
            }
            if (components.length > 0) {
                if (components.includes('MenuItem')) {
                    console.log("装载MenuItem")
                    app.component('MenuItem', MenuItem)
                }
            }
            app.component('MuShowImg', MuShowImg)
            app.component('MuTreeInput', MuTreeInput)
            app.component('MuFileUpload', MuFileUpload)
            app.component('MuAvatarUpload', MuAvatarUpload)
            app.component('MuCascader', MuCascader)
            app.component('MuTreeSelect', MuTreeSelect)
            app.component('MuIcon', MuIcon)
            if (isIndex) {
                let that = this;
                window.getThumb = function () {
                    return that.config.color
                }
            } else {
                let that = this;
                window.addEventListener('message', function (event) {
                    let data = event.data;
                    if (data.action) {
                        switch (data.action) {
                            case 'changeTheme':
                                that.changeTheme(data.data)
                                break;
                        }
                    }
                })
                if (parent?.window?.getThumb) {
                    let themeObj = parent.window.getThumb()
                    this.changeTheme(themeObj)
                }

            }

            console.log("加载完成")
        },
        loadingIndexData(list) {
            // console.log('loadingIndexData')
            let data = {};
            if (list.seachObj && list.seachObj.length > 0) {
                data = this.getParamet(list.seachObj)
            }
            // console.log(data,'======================')
            data.page = list.page ? list.page : 1
            data.limit = list.limit ? list.limit : 10
            let url = Config.sub_url
            return this.sendGet(url, data, true)
        },
        getParamet(obj = []) {
            let newObj = {}
            let filter = {}
            let op = {}
            for (let i = 0; i < obj.length; i++) {
                if (obj[i].value != '' && obj[i].value != null) {
                    if (this.config.notInField.includes(obj[i].name)) {
                        newObj[obj[i].name] = obj[i].value
                    } else {
                        filter[obj[i].name] = obj[i].value
                        op[obj[i].name] = obj[i].seach_type ? obj[i].seach_type : '='
                    }
                }
            }
            newObj.filter = filter
            newObj.op = op
            return newObj
        },
        edit(row, idField = 'id', area = ['50%', '80%']) {
            let that = this;
            let url = this.getActionUrl('edit', {ids: row[idField]})
            console.log(url)
            layer.open({
                type: 2,
                title: '编辑',
                area: area,
                content: url,
                end: function (layero, index) {
                    // console.log("处理成功")
                    // let iframeWin = window[layero.find('iframe')[0]['name']];
                    // iframeWin.setData(row)
                    if (that.refresh) {
                        that.refresh()
                    }
                }
            })
        },
        open(url, callback=null, title = '新增', area = ['50%', '80%']){
            if((typeof callback)==='string'){
                title = callback
                callback = null
            }
            if((typeof callback)==='object'){
                area = callback
                callback = null
            }
            window.callback = callback
            layer.open({
                type: 2,
                title: title,
                area: area,
                content: url,
                end:function (){
                    console.log('完成')
                }
            })
        },
        cancel() {
            // console.log(99999999)
            var index = parent.layer.getFrameIndex(window.name)
            parent.layer.close(index);
        },
        async onEditSubmit(form) {
            // console.log(form)
            // return
            let url = Config.sub_url
            let res = await common.sendPost(url, {row: form})
            if (res.code != 1) {
                await ElMessage.error(res.msg)
            }else{
                await common.successMessage(res.msg)
                var index = parent.layer.getFrameIndex(window.name)
                parent.layer.close(index);
            }
        },
        async onAddSubmit(form) {
            // console.log(form)
            // return
            let url = Config.sub_url
            let res = await common.sendPost(url, {row: form})
            if (res.code != 1) {
                await ElMessage.error(res.msg)
            }else{
                await common.successMessage(res.msg)
                var index = parent.layer.getFrameIndex(window.name)
                parent.layer.close(index);
            }
        },
        async changeSwitch(row,pk='id',field='status'){
            // console.log(row,'rrrrrrrrrrrr')
            let ids = ''
            if((typeof row)==='string'||(typeof row)==='number'){
                ids = row
            }else{
                ids = row[pk]
            }
            let url =  common.getActionUrl('multi', {ids:ids});
            let res = await common.sendPost(url, {field:field})
            if(res.code == 1){
                let that = this
                await common.successMessage(res.msg)
                if(common.refresh){
                    common.refresh()
                }
            }else{
                common.errorMessage(res.msg)
            }
        },
        async del(row, pk = 'id') {
            let ids = ""
            if((typeof row)==='string'|| (typeof row)==='number'){
                ids = row
            }else{
                ids = row[pk]
            }
            let that = this;
            let url = common.getActionUrl('del', {ids:ids})
            let rconfirm = await  ElMessageBox.confirm('确定删除吗？', '提示');
            if(rconfirm==='confirm'){
                let res = await common.sendPost(url, {})
                if(res.code == 1){
                    await common.successMessage(res.msg)
                    if (that.refresh) {
                        that.refresh()
                    }
                }else{
                    await common.errorMessage(res.msg)
                }
            }
        },
        add(url = '', area = ['50%', '80%']) {
            if (!url) {
                url = 'add'
            }
            url = common.getActionUrl(url)
            let that = this;
            layer.open({
                type: 2,
                title: '添加',
                area: area,
                content: url,
                end: function () {
                    // console.log("处理成功")
                    if (that.refresh) {
                        that.refresh()
                    }
                    // let iframeWin = window[layero.find('iframe')[0]['name']];
                    // iframeWin.setData(row)
                }
            })
        },
        getFilePath(url) {
            if (!url) {
                return ''
            }
            if (url.indexOf('http') !== -1) {
                return url
            }
            let cdnurl = Config.upload.cdnurl
            if (cdnurl == '') {
                return cdnurl + '/' + url
            } else {
                if (cdnurl.charAt(cdnurl.length - 1) == '/') {
                    return cdnurl + url
                } else {
                    return cdnurl + '/' + url
                }
            }
        },
        /**
         * 设置监听事件
         * @param event
         * @param clallBack
         */
        setEventListener(event, clallBack) {
            window.addEventListener(event, clallBack)
        },
        /**
         * 触发事件
         * @param event
         * @param data
         */
        eventListener(event, data) {
            return window.dispatchEvent(new CustomEvent(event, {detail: data}))
        },
        /**
         * 修改主题色
         * @param str
         */
        changeTheme(obj) {
            if (!obj) {
                return
            }
            if (typeof obj === 'string') {
                this.config.color['--el-color-primary'] = obj
                this.config.color['--el-color-primary-light-3'] = obj
                this.config.color['--el-color-primary-dark-2'] = obj
                document.documentElement.style.setProperty('--el-color-primary', obj);
                document.documentElement.style.setProperty('--el-color-primary-light-3', obj);
                document.documentElement.style.setProperty('--el-color-primary-dark-2', obj);
            } else {
                for (let key in obj) {
                    document.documentElement.style.setProperty(key, obj[key]);
                    this.config.color[key] = obj[key]
                }
            }
        },
        /**
         * 获取action的url
         * @param action
         * @param data
         * @returns {string}
         */
        getActionUrl(action, data = {}) {
            let url = ''
            if (Config.config_array.addons) {
                url = '/addons/' + Config.config_array.addons + '/' + Config.config_array.module + '/' + Config.config_array.controller + '/' + action
            } else {
                url = '/' + Config.config_array.module + '/' + Config.config_array.controller + '/' + action
            }
            if (url.indexOf('?') != -1) {
                for (let key in data) {
                    url += '&' + key + '=' + data[key]
                }
            } else {
                let ins = 0
                for (let key in data) {
                    if (ins == 0) {
                        url = url + '?' + key + '=' + data[key]
                        // url += key+'='+data[key]
                        ins++;
                    } else {
                        url += '&' + key + '=' + data[key]
                    }
                }
            }
            return url
        },
        /**
         * 成功提示
         * @param message
         * @param callBack
         * @param timeOut
         */
        async successMessage(message, callBack = null, timeOut = 1000) {
            await  ElMessage({
                type: 'success',
                message: message,
                duration: timeOut,
            })
            if (callBack) {
                callBack()
            }
        },
        /**
         * 错误提示
         * @param message
         * @param callBack
         * @param timeOut
         */
        errorMessage(message, callBack = null, timeOut = 1000) {
            ElMessage({
                type: 'error',
                message: message,
                duration: timeOut,
                onClose: function () {
                    // console.log('error')
                    if (callBack) {
                        callBack()
                    }
                }
            })
        },
        /**
         * 提交请求
         * @param action
         * @param data
         * @returns {*}
         */
        sendSubmit(action = '', data = null, loading = true) {
            if (action === '') {
                action = Config.sub_url
            }
            if (data === null) {
                if (form) {
                    data = form.value
                } else {
                    data = {}
                }
            }
            return this.sendAjax(this.getActionUrl(action), data, 'POST', loading)
        },
        /**
         * 发送ajax
         * @param url
         * @param data
         * @param method
         * @returns {Promise}
         */
        sendAjax(url, data = {}, method = 'POST', loading = false) {
            if (method == 'POST' || method == 'post') {
                return this.sendPost(url, data, loading)
            }
            return this.sendGet(url, data, loading)
        },
        /**
         * 发送get请求
         * @param url
         * @param data
         * @param loading
         * @returns {Promise}
         */
        sendGet(url = '', data = {}, loading = false) {
            if (url === '') {
                url = Config.sub_url
            }
            return new Promise((resolve, reject) => {
                let loadingInstance = null
                if (loading) {
                    loadingInstance = ElLoading.service({
                        lock: true,
                        text: 'Loading',
                        background: 'rgba(0, 0, 0, 0.05)'
                    })
                }
                $.get(url, data, (res) => {
                    if (loading) {
                        loadingInstance.close()
                    }
                    if (res.code == 1) {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        /**
         * 发送post请求
         * @param url
         * @param data
         * @returns {Promise}
         */
        sendPost(url = '', data = {}, loading = false) {
            if (url === '') {
                url = Config.sub_url
            }
            return new Promise((resolve, reject) => {
                let loadingInstance = null
                if (loading) {
                    loadingInstance = ElLoading.service({
                        lock: true,
                        text: 'Loading',
                        background: 'rgba(0, 0, 0, 0.05)'
                    })
                }
                $.post(url, data, (res) => {
                    if (loading) {
                        loadingInstance.close()
                    }
                    if (res.code == 1) {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        getTime(str) {
            // console.log(str)
            if ((typeof str) === 'number' || (!isNaN(str) && typeof str === 'string' && str.trim() !== "")) {
                str = parseInt(str) * 1000;
                // console.log(str, 'jjjjjjjjjjjjjj')
                const date = new Date(str);
                console.log(date)

                // 获取年、月、日、小时、分钟和秒
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以加1
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                console.log(year)
                // 拼接成所需的格式
                str = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                return str;
            } else {
                return str
            }
        },
        getQueryParamsAsObject(){
            const params = new URLSearchParams(location.search);
            return Object.fromEntries(params);
        }
    }
    return common
})